#include "drvExtflash.h"
#include "stm32f7xx_hal.h"

#define QSPI_FLASH_SIZE 25
#define QUAD_INOUT_FAST_READ_4_BYTE_ADDR_CMD 0xEC /* 32bit地址的4线快速读取命令 */

QSPI_HandleTypeDef QSPIHandle;

void drvQspiFlashInit(void)
{
	QSPIHandle.Instance = QUADSPI;	
	QSPIHandle.Init.ClockPrescaler = 1;//设置时钟速度，QSPI clock = 200MHz / (ClockPrescaler+1) = 100MHz
	QSPIHandle.Init.FifoThreshold = 32;//设置FIFO阀值，范围1 - 32	
	QSPIHandle.Init.SampleShifting = QSPI_SAMPLE_SHIFTING_HALFCYCLE;//在外部信号延迟时，这有利于推迟数据采样
	QSPIHandle.Init.FlashSize = QSPI_FLASH_SIZE; //Flash大小是2^(FlashSize + 1) = 2^26 = 64MB
	QSPIHandle.Init.ChipSelectHighTime = QSPI_CS_HIGH_TIME_2_CYCLE;
	QSPIHandle.Init.ClockMode = QSPI_CLOCK_MODE_0;
	QSPIHandle.Init.FlashID = QSPI_FLASH_ID_1;
	QSPIHandle.Init.DualFlash = QSPI_DUALFLASH_DISABLE;
	/* 初始化配置QSPI */
	HAL_QSPI_Init(&QSPIHandle);

    QSPI_CommandTypeDef s_command = {0};
    QSPI_MemoryMappedTypeDef s_mem_mapped_cfg = {0};
    /* 基本配置 */
    s_command.InstructionMode = QSPI_INSTRUCTION_1_LINE; /* 1线方式发送指令 */ 
    s_command.AddressSize = QSPI_ADDRESS_32_BITS; /* 32位地址 */
    s_command.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE; /* 无交替字节 */
    s_command.DdrMode = QSPI_DDR_MODE_DISABLE; /* W25Q256JV不支持DDR */
    s_command.DdrHoldHalfCycle = QSPI_DDR_HHC_ANALOG_DELAY; /* DDR模式，数据输出延迟 */
    s_command.SIOOMode = QSPI_SIOO_INST_EVERY_CMD; /* 每次传输都发指令 */
    
    /* 全部采用4线 */
    s_command.Instruction = QUAD_INOUT_FAST_READ_4_BYTE_ADDR_CMD; /* 快速读取命令 */
    s_command.AddressMode = QSPI_ADDRESS_4_LINES; /* 4个地址线 */
    s_command.DataMode = QSPI_DATA_4_LINES; /* 4个数据线 */
    s_command.DummyCycles = 6; /* 空周期 */

    /* 关闭溢出计数 */
    s_mem_mapped_cfg.TimeOutActivation = QSPI_TIMEOUT_COUNTER_DISABLE;
    s_mem_mapped_cfg.TimeOutPeriod = 0;

    HAL_QSPI_MemoryMapped(&QSPIHandle, &s_command, &s_mem_mapped_cfg);
}

void drvQspiFlashDeInit(void)
{

}